package org.ymjava.medical.admin.web;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.ymjava.medical.admin.annotation.LoginAdmin;
import org.ymjava.medical.admin.constant.PermType;
import org.ymjava.medical.admin.util.StatVo;
import org.ymjava.medical.admin.vo.Json;
import org.ymjava.medical.core.util.ResponseUtil;
import org.ymjava.medical.db.AllPackage.biz.SysPermBiz;
import org.ymjava.medical.db.AllPackage.biz.SysRoleBiz;
import org.ymjava.medical.db.AllPackage.biz.SysRolePermBiz;
import org.ymjava.medical.db.AllPackage.biz.SysUserRoleBiz;
import org.ymjava.medical.db.AllPackage.entity.SysPerm;
import org.ymjava.medical.db.AllPackage.entity.SysRole;
import org.ymjava.medical.db.AllPackage.entity.SysRolePerm;
import org.ymjava.medical.db.AllPackage.entity.SysUserRole;
import org.ymjava.medical.db.AllPackage.rest.BaseController;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/admin/role")
public class SysRoleController extends BaseController<SysRoleBiz,SysRole> {

	@Autowired
	private SysUserRoleBiz sysUserRoleBiz;

	@Autowired
	private SysPermBiz sysPermBiz;

	@Autowired
	private SysRolePermBiz sysRolePermBiz;

	@PostMapping("/deleteRole")
	public Object delete(@LoginAdmin Integer adminId,@RequestBody SysRole sysRoles ) {
		if (adminId == null) {
			return ResponseUtil.unlogin();
		}
		baseBiz.deleteById(sysRoles.getRid());
		return ResponseUtil.ok();
	}
	@PostMapping("/addRole")
	public Object create(@LoginAdmin Integer adminId,@RequestBody SysRole sysRoles ){
		if (adminId == null) {
			return ResponseUtil.unlogin();
		}
		String rname=sysRoles.getRname();
		rname = rname.replaceAll(" ", "");
		sysRoles.setRname(rname);
		List<SysRole> sysRoles1=baseBiz.queryByRname(rname);
		if(sysRoles1.size() > 0){
			return ResponseUtil.fail(403, "角色名已注册");
		}
		sysRoles.setCreated(new Date());
		baseBiz.insertSelective(sysRoles);
		return ResponseUtil.ok(sysRoles);
	}
	@PostMapping("/updateUserRole")
	public Object updateUserRole(@LoginAdmin Integer adminId,@ RequestBody String body){
		if (adminId == null) {
			return ResponseUtil.unlogin();
		}
		JSONObject json = JSON.parseObject(body);
		final String uid = json.getString("user_id");
		List<String> rids = json.getJSONArray("role_id").toJavaList(String.class);
		Integer iuid = Integer.valueOf(uid);

		//删除：原来绑定的角色
		sysUserRoleBiz.deleteUserRole(iuid);

		//更新：绑定新的角色
		for (int i=0;i<rids.size();i++){
			String roleid=rids.get(i);
			Integer iroleid=Integer.valueOf(roleid);
			SysUserRole sysUserRole = new SysUserRole();
			sysUserRole.setRoleId(iroleid);
			sysUserRole.setUserId(iuid);
			sysUserRoleBiz.insert(sysUserRole);
		}

		return ResponseUtil.ok();
	}
	@PostMapping("/update")
	public Object update(@LoginAdmin Integer adminId,@RequestBody SysRole sysRoles ){
		if (adminId == null) {
			return ResponseUtil.unlogin();
		}
		String rname=sysRoles.getRname();
		rname = rname.replaceAll(" ", "");
		sysRoles.setRname(rname);
		List<SysRole> sysRoles1=baseBiz.queryByRname(rname);
		if(sysRoles1.size() > 0){
			return ResponseUtil.fail(403, "角色名已注册");
		}
		sysRoles.setUpdated(new Date());
		baseBiz.updateSelectiveById(sysRoles);
		return ResponseUtil.ok(sysRoles);
	}

	@GetMapping("/query")
	public Object list(@LoginAdmin Integer adminId,
		String rname,
		@RequestParam(value = "page", defaultValue = "1") Integer page,
		@RequestParam(value = "limit", defaultValue = "10") Integer limit,
		String sort, String order) {
		if (adminId == null) {
			return ResponseUtil.unlogin();
		}
		return ResponseUtil.ok(baseBiz.queryAll(rname,page,limit,sort,order));
	}

	@GetMapping("/getAllRole")
	public Object getAllRole(@LoginAdmin Integer adminId){
		if (adminId == null) {
			return ResponseUtil.unlogin();
		}
		List<SysRole> sysRoles = baseBiz.selectListAll();
		Map<String, Object> data = new HashMap<>();
		data.put("items", sysRoles);
		return ResponseUtil.ok(data);
	}

	@GetMapping("getRoleByUser")
	public Object rolebyuser(@LoginAdmin Integer adminId,String id){
		if (adminId == null) {
			return ResponseUtil.unlogin();
		}

		List<Map> rows = baseBiz.getUserRole(id);
		StatVo statVo = new StatVo();
		statVo.setRows(rows);

		return ResponseUtil.ok(statVo);
	}

	@GetMapping("/{rid}/perms")
	public Object findRolePerms(@PathVariable String rid){
		String oper = "find role perms";
		if (StringUtils.isBlank(rid)){
			return Json.fail(oper, "无法查询当前角色的权限值：参数为空（角色id）");
		}
		Integer rids = Integer.valueOf(rid);
		SysRole role = baseBiz.selectById(rids);
		List<SysPerm> perms = sysPermBiz.getPermsByRoleId(rids);
		Map<Integer, List<SysPerm>> permMap = perms.stream().collect(Collectors.groupingBy(SysPerm::getPtype));

		List<String> menuPvals = permMap.getOrDefault(PermType.MENU, new ArrayList<>()).stream()
			.filter(perm->perm.getLeaf()==1).map(SysPerm::getPval).collect(Collectors.toList());

		Map<String, Object> data = new HashMap<>();
		data.put("role" ,role);
		data.put("menuPvals", menuPvals);
		return ResponseUtil.ok(data);
	}

	@PostMapping("/perm")
	public Object updateRolePerm(@RequestBody String  body) {

		String oper = "update role's permissions";

		JSONObject json = JSON.parseObject(body);
		final Integer ptype = json.getInteger("ptype");
		final Integer rid = json.getInteger("rid");
		List<String> pvals = json.getJSONArray("pvals").toJavaList(String.class);
		if(pvals.size()==0){
			return ResponseUtil.ok();
		}else{
			// 删除相应的数据
			sysRolePermBiz.deleteByidPtype(rid,ptype);

			// 插入数据
			for(int i=0;i<pvals.size();i++){
				String pval = pvals.get(i);
				SysRolePerm sysRolePerm = new SysRolePerm();
				sysRolePerm.setPermType(ptype);
				sysRolePerm.setPermVal(pval);
				sysRolePerm.setRoleId(rid);
				sysRolePermBiz.insert(sysRolePerm);
			}
			return ResponseUtil.ok();
		}
	}

	@PostMapping("/permsss")
	public Json addPerm(@RequestBody String body){
		String oper="add role's permissions";
		JSONObject json = JSON.parseObject(body);
		String rid = json.getString("rid");
		Integer rids = Integer.valueOf(rid);
		Integer ptype = json.getInteger("ptype");
		String pval = json.getString("pval");

		//	    SysRolePerm sysRolePerm = new SysRolePerm();
		//	    sysRolePerm.setRoleId(rids);
		//	    sysRolePerm.setPermType(ptype);
		//	    sysRolePerm.setPermVal(pval);
		//	    litemallRolePermService.insertRolePerm(sysRolePerm);
		return Json.result(oper,true);
	}

	@DeleteMapping("/perm")
	public Json deletePerm(@RequestBody String body){
		String oper = "delete role's permissions";

		JSONObject json = JSON.parseObject(body);
		String rid = json.getString("rid");
		Integer rids = Integer.valueOf(rid);
		Integer ptype = json.getInteger("ptype");
		String pval = json.getString("pval");
		SysRolePerm sysRolePerm = new SysRolePerm();
		sysRolePerm.setPermType(ptype);
		sysRolePerm.setPermVal(pval);
		sysRolePerm.setRoleId(rids);
		sysRolePermBiz.delete(sysRolePerm);
		return Json.succ(oper,true);
	}
}